package com.lottery.service.pc28.lobbyService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.pc28.accoutDao.UserDao;
import com.lottery.dto.Message;
import com.lottery.dto.MessageTube;
import com.lottery.entity.User;
import com.lottery.service.pc28.InitData;
import com.lottery.service.pc28.lobbyService.BetNoticeService;
import com.lottery.utils.MessageTubes;
import com.lottery.utils.TouristData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class BetNoticeServiceImpl implements BetNoticeService {
    @Autowired
    private UserDao userDao;

    private MessageTubes messageTubes = MessageTubes.getInstance();

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 插入下注弹幕
     *
     * @param userId  用户id
     * @param barrage 要插入的弹幕
     * @return
     */
    public String insertBetNotice(int userId, String barrage, int lotteryType) {
        logger.debug("下注弹幕插入={}", userId + "  " + barrage);
        JSONObject jObject = new JSONObject();
        User selectId = null;
        try {
            selectId = userDao.selectId(userId);
        } catch (Exception e) {
            jObject.put("result", "1");
            jObject.put("msg", "插入弹幕失败");
            return jObject.toJSONString();
        }
        String body = userId + "::" + selectId.getUserName() + "::" + selectId.getHeadPic() + "::" + barrage;
        Message message = new Message();
        message.setMessageBody(body);
        message.setType("0");
        message.setTimestamp(new Date().getTime());

        MessageTube messageTube;
		/*if (lotteryType == 1) {
			messageTube = messageTubes.getSscBetMessageTube();
		} else {
			messageTube = messageTubes.getPc28BetMessageTube();
		}*/
        //根据agenyId查出对应的消息通道
        String agencyId = selectId.getAgencyId();
        String judge = lotteryType+"bet";
        messageTube = InitData.MESSAGE_GROUP.get(agencyId).get(judge);


        int push = messageTube.push(message);
        logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);
        logger.debug("返回的index是={},插入管道={}", push, queryBetNotice(-1, lotteryType, agencyId));
        jObject.put("result", "0");
        jObject.put("msg", "插入弹幕成功");
        return jObject.toJSONString();
    }

    /**
     * 插入提示弹幕
     *
     * @param barrage 要插入的弹幕
     * @return
     */
    public void insertPromptNotice(String barrage, int lotteryType) {
        logger.debug("下注弹幕插入开奖信息={}", barrage);
        Message message = new Message();
        message.setMessageBody(barrage);
        message.setType("1");
        message.setTimestamp(new Date().getTime());
        logger.debug("要插入管道的信息={}", message);

        MessageTube messageTube;
        if (lotteryType == 1) {
            messageTube = messageTubes.getSscBetMessageTube();
        } else {
            messageTube = messageTubes.getPc28BetMessageTube();
        }

        int push = messageTube.push(message);
        logger.debug("return index={},{},{},{}", messageTube.getHashCode(), push, message.getType(), barrage);
        /*logger.debug("返回的index是={}, 插入管道成功={}", push, queryBetNotice(-1, lotteryType));*/
    }

    /**
     * 获得下注弹幕
     *
     * @param index 上次查询最后一条记录的index
     * @return
     */
    public String queryBetNotice(int index, int lotteyType, String agencyId) {
        Map<String, Object> maxmap = new HashMap<String, Object>();
        // List<Message> checkMessage2 = new ArrayList<>();
        try {
            // 获得上次到现在的所有弹幕
            List<Message> checkMessage;
           /* if (lotteyType == 1) { // 时时彩
                checkMessage = messageTubes.getSscBetMessageTube().checkMessage(index + 1);
            } else { // PC28
                checkMessage = messageTubes.getPc28BetMessageTube().checkMessage(index + 1);
            }*/
            String judge = lotteyType + "bet";
            checkMessage = InitData.MESSAGE_GROUP.get(agencyId).get(judge).checkMessage(index + 1);

            ArrayList<Map<String, String>> listMap = new ArrayList<>();
            if (checkMessage == null) {
                maxmap.put("array", listMap);
                maxmap.put("message", index + "");
                maxmap.put("result", "0");
                maxmap.put("msg", "成功");
                return JSON.toJSONString(maxmap, true);
            }

            // 截取2分钟 以内的信息
            // for (int i = 0; i < checkMessage.size(); i++) {
            // if (time - checkMessage.get(i).getTimestamp() <= 120000) {
            // List<Message> subList = checkMessage.subList(i, checkMessage.size());
            // logger.debug("查询下注弹幕,2分钟以内={}", subList);
            long time = new Date().getTime();
            int reIndex = 0;
            for (Message message : checkMessage) {
                if (time - message.getTimestamp() > 120000) {
                    continue;
                }
                Map<String, String> map = new HashMap<String, String>();
                String messageBody = message.getMessageBody();
                if (message.getType().equals("0")) {
                    String[] split = messageBody.split("::");
                    map.put("userId", split[0]);
                    map.put("userName", split[1]);
                    map.put("headPic", split[2]);
                    map.put("barrage", split[3]);
                } else {
                    map.put("barrage", messageBody);
                }
                listMap.add(map);
                reIndex = message.getIndex();
            }
            maxmap.put("array", listMap);
            maxmap.put("message", reIndex + "");
            maxmap.put("result", "0");
            maxmap.put("msg", "成功");
            return JSON.toJSONString(maxmap, true);
        } catch (Exception e) {
            maxmap.put("result", "1");
            maxmap.put("msg", "失败");
            logger.error("queryBetNotice error:", e);
        }
        return JSON.toJSONString(maxmap, true);
    }

    public void tourBetnotice(int userId, String mStr, int lotteyType) {
        String body = userId + "::" + TouristData.touristInfo.get(userId).getTouristName() + "::" + 0 + "::" + mStr;
        Message message = new Message();
        message.setMessageBody(body);
        message.setType("0");
        message.setTimestamp(new Date().getTime());
        MessageTube messageTube = null;
        if (lotteyType == 1) {
            messageTube = MessageTubes.getInstance().getSscBetMessageTube();
        } else if (lotteyType == 2) {
            messageTube = MessageTubes.getInstance().getPc28BetMessageTube();
        }

        int push = messageTube.push(message);
        logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);
    }
}
